package com.credithc.signature.job.handler;

import com.credithc.signature.common.service.SignatureLogService;
import com.credithc.signature.job.configure.props.SignatureProps;
import com.credithc.signature.job.ro.CallRequest;
import com.credithc.signature.job.ro.HandleRequest;
import com.credithc.signature.job.ro.JobRequest;
import com.credithc.signature.job.service.UploadPDFService;
import com.credithc.signature.job.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Objects;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年06⽉25⽇<br/>
 * @version：v1.0.0<br>
 */
@Slf4j
public class UploadFileHandler extends AbstractExecuteHandler {

    private String handlerName = "合同上传";

    @Autowired
    private static SignatureProps props;

    @Autowired
    private static UploadPDFService uploadPDFService;

    static {
        uploadPDFService = SpringUtil.getBean(UploadPDFService.class);
        props = SpringUtil.getBean(SignatureProps.class);
    }

    public UploadFileHandler() {
        this.handlerName = handlerName;
    }

    @Override
    public void handleRequest(HandleRequest handleRequest) throws Exception {
        if (Objects.nonNull(handleRequest)) {
            JobRequest jobRequest = handleRequest.getJobRequest();
            String requestSn = jobRequest.getRequestSn();
            try {
                // 1、文件上传
                String pdfPath = uploadPDFAndResumption(handleRequest.getJobRequest(), handleRequest.getPdfPath());
                log.info("－消息－:requestSn={},【{}】已经处理;流程结束", requestSn, handlerName);

                // 2、判断是否有下一个
                CallRequest callRequest = new CallRequest();
                BeanUtils.copyProperties(jobRequest,callRequest);
                callRequest.setCallBackURL(jobRequest.getCallbackUrl());
                callRequest.setRequestSN(requestSn);
                callRequest.setIsSuccess(true);
                callRequest.setContractUri(pdfPath);
                callRequest.setErrorMsg("签章成功");
                handleRequest.setCallRequest(callRequest);
                hasNextHandler(requestSn, handleRequest);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("－消息－:requestSn={},执行【{}】流程时发生异常;总流程结束\n{}", requestSn, handlerName, e.getCause());
                this.setNextHandler(new CallbackHandler());
                CallRequest callRequest = new CallRequest();
                BeanUtils.copyProperties(jobRequest,callRequest);
                callRequest.setCallBackURL(jobRequest.getCallbackUrl());
                callRequest.setRequestSN(requestSn);
                callRequest.setIsSuccess(false);
                callRequest.setErrorMsg(e.getMessage());
                handleRequest.setCallRequest(callRequest);
                this.nextHandler.handleRequest(handleRequest);
            }
        }
    }

    /**
     * 判断是否还有下一个流程:如果有，则继续执行
     */
    private void hasNextHandler(String requestSn, HandleRequest handleRequest) throws Exception {
        if (null != this.nextHandler) {
            this.nextHandler.handleRequest(handleRequest);
        } else {
            log.info("－消息－:requestSn={},【{}】无下一个执行流程;总流程结束", requestSn, handlerName);
            return;
        }
    }

    /**
     * 文件上传操作
     *
     * @param coreRequet
     * @param pdfPath
     * @return
     * @throws Exception
     */
    private String uploadPDFAndResumption(JobRequest coreRequet, String pdfPath) throws Exception {
        if (StringUtils.isEmpty(pdfPath)) {
            return null;
        }
        long startUpload = System.currentTimeMillis();
        for (int uploadTryCount = 0; uploadTryCount <= props.uploadTryTimes; uploadTryCount++) {
            try {
                pdfPath = uploadPDFService.uploadPDF(pdfPath, coreRequet);
                break;
            } catch (Exception e) {
                if (uploadTryCount >= props.uploadTryTimes) {
                    long endUpload = System.currentTimeMillis();
                    log.error("－消息－: requestSn={},上传PDF耗时:{}毫秒,重试次数:{}", coreRequet.getRequestSn(), (endUpload - startUpload), uploadTryCount);
                    throw new RuntimeException(e);
                }
            }
        }
        long endUpload = System.currentTimeMillis();
        log.debug("－消息－: requestSn={},上传PDF成功,耗时:{}毫秒", coreRequet.getRequestSn(), (endUpload - startUpload));
        return pdfPath;
    }
}
